import { useUserStore } from '@/store/modules/user/user';
import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';
import { ResponseBody } from '@/api/typing';
import { message } from 'ant-design-vue';
import router from '@/router';
import moment from 'moment';

const request = axios.create({
	timeout: 30000,
});

axios.defaults.headers.post['Content-Type'] = 'application/json';

//异常拦截处理器
const errorHandler = (error: AxiosError): Promise<any> => {
	let response = null;
	if (error.response) {
		const { status } = error.response;
		// 403 无权限
		if (status === 403) {
			message.warning('请先登录！', 3);
			router.push({ name: 'login' });
			return Promise.resolve(error);
		}
		const { data } = error.response as any;
		if (data) {
			response = data;
		}
	}
	return Promise.resolve(response);
};

//请求拦截器
const requestHandler = (
	config: AxiosRequestConfig<any>,
): AxiosRequestConfig<any> | Promise<AxiosRequestConfig<any>> | any => {
	const userStore = useUserStore();
	const token = userStore.getToken;
	if (token) {
		if (config?.headers) {
			config.headers['Authorization'] = token;
		}
	} else {
		router.push({ name: 'login' });
	}
	if (config?.data) {
		for (const k in config.data) {
			if (config.data[k] && config.data[k].$L == 'zh-cn') {
				config.data[k] = config.data[k].add(8, 'hours');
			}
		}
	}
	return config;
};

//请求拦截器
const requestHandlerFile = (
	config: AxiosRequestConfig<any>,
): AxiosRequestConfig<any> | Promise<AxiosRequestConfig<any>> | any => {
	const userStore = useUserStore();
	const token = userStore.getToken;
	if (token) {
		if (config?.headers) {
			config.headers['Authorization'] = token;
			config.headers['Content-Type'] = 'multipart/form-data';
		}
	} else {
		router.push({ name: 'login' });
	}
	if (config?.data) {
		for (const k in config.data) {
			if (config.data[k] && config.data[k] instanceof Date) {
				config.data[k] = moment(config.data[k])
					.add(8, 'hours')
					.local()
					.toISOString();
			}
		}
	}
	return config;
};

// 添加请求拦截器
request.interceptors.request.use(requestHandler, errorHandler);

//响应拦截器
const responseHandler = (
	response: AxiosResponse<any>,
): ResponseBody<any> | AxiosResponse<any> | Promise<any> | any => {
	// 如果是文件下载（检查 Content-Type 或请求路径）
	if (
		response.config.url?.includes('/export') ||
		response.headers['content-type'] ===
			'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
	) {
		return response; // 返回整个 response 包含 Blob 数据
	}
	const { data } = response;
	if (data.code == 403) {
		router.push({ name: 'login' });
		return;
	}
	return data;
};

// 添加响应拦截器
request.interceptors.response.use(responseHandler, errorHandler);

const requestFile = axios.create({
	timeout: 30000,
});

// 添加请求拦截器
requestFile.interceptors.request.use(requestHandlerFile, errorHandler);

requestFile.interceptors.response.use(responseHandler, errorHandler);

export { request as default, requestFile };
